package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1. 创建搜索请求
            SearchRequest request = new SearchRequest("hotel");
            // 1.1 构建查询条件
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params,source);
            // 设置分页
            source.from((params.getPage() - 1) * params.getSize() );
            source.size(params.getSize());

            // 判断location是否有值，如果有值按照距离排序
            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)) {
                source.sort(
                        SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                                    .order(SortOrder.ASC)
                                    .unit(DistanceUnit.KILOMETERS)
                );
            }
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
            // 2. 执行搜索请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 3. 解析响应结果
            SearchHits hits = response.getHits();
            PageResult pageResult = new PageResult();
            // 设置查询结果数量
            pageResult.setTotal(hits.getTotalHits().value);
            List<HotelDoc> list = new ArrayList<>();
            // 遍历文档列表
            for (SearchHit hit : hits) {
                // 获取每个文档的source内容(文档json字符串)  ==> 转为 HotelDoc文档java对象
                HotelDoc hotelDoc = JSON.parseObject(hit.getSourceAsString(), HotelDoc.class);
                // 如果有排序字段，获取排序字段中距离的值
                if (StringUtils.isNotBlank(location)) {
                    Object[] sortValues = hit.getSortValues();
                    if(sortValues!=null && sortValues.length>0){
                        hotelDoc.setDistance(sortValues[0]);
                    }
                }
                list.add(hotelDoc);
            }
            pageResult.setHotels(list);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("es搜索出错了");
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1. 创建搜索请求
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            // 2. 设置query查询条件
            buildBasicQuery(params,source);
            // 3. 设置size = 0
            source.size(0);
            // 4. 设置 聚合请求条件   brand分组  city分组  starName分组
            buildAggregations(source);
            // 5. 执行聚合搜索请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 6. 解析响应内容 获取聚合结果 brand分组  city分组  starName分组
            // 6.1 获取总的聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            List<String> starNameList = getAggByName(aggregations,"starNameAgg");
            // 7. 将结果封装成 Map<String,List<String>>
            Map<String,List<String>> map = new HashMap<>();
            map.put("brand",brandList);
            map.put("city",cityList);
            map.put("starName",starNameList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("聚合查询失败");
        }
    }

    @Override
    public List<String> suggestion(String key) {
        try {
            // 1. 创建请求
            SearchRequest request = new SearchRequest("hotel");
            // 2. 添加suggest搜索条件
            SearchSourceBuilder source = request.source();
            // 3. 搜索索引库中 suggestion字段中  以 key为前缀的所有词条   (只显示前10个词条)
            source.suggest(
                    new SuggestBuilder()
                            .addSuggestion(
                                    "mySuggestion",  // 自定义的查询名称
                                    SuggestBuilders.completionSuggestion("suggestion")
                                                    .prefix(key)  // 匹配前缀为key的词条
                                                    .skipDuplicates(true) // 去除重复的词条
                                                    .size(10) // 保留10条
                            )
            );
            // 4. 执行请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 查询suggest结果
            Suggest suggest = response.getSuggest();
            // 根据自定义的名称 找到具体的suggest结果
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
            // 获取options 遍历options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> suggestionList = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                suggestionList.add(option.getText().toString());
            }
            return suggestionList;
//            List<String> collect = options.stream()
//                    .map(option -> option.getText().toString())
//                    .collect(Collectors.toList());

            // 5. 解析响应结果
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("自动补全查询失败");
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param aggregations  聚合结果对象
     * @param aggName    自定义的聚合名称
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations,String aggName) {
        // 6.2 获取指定聚合结果
        Terms aggResult = aggregations.get(aggName);
        // 6.3 获取结果中的分组信息 buckets
        List<? extends Terms.Bucket> buckets = aggResult.getBuckets();
        // 6.4 遍历分组  得到分组内容
        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 获取每个分组的key 加入到集合
            resultList.add(bucket.getKeyAsString());
        }
        // 将集合返回
        return resultList;
    }

    /**
     * 构建聚合条件
     * @param source
     */
    private void buildAggregations(SearchSourceBuilder source) {
        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("cityAgg")
                        .field("city")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("starNameAgg")
                        .field("starName")
                        .size(20)
        );
    }

    /**
     * 用于构建 Query查询条件
     * @param params
     * @param source
     */
    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {
        // 构建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(params.getKey())) {
            // 如果 key为空 就查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // 如果 key不为空  使用match  查询 all字段
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        // 如果城市不为空  使用term查询 city字段
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }
        // 如果星级不为空  使用term查询 star字段
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }
        // 如果品牌不为空  使用term查询 brand字段
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        // 如果价格不为空  使用range查询 price字段
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if(minPrice!=null && maxPrice!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lt(maxPrice));
        }
        // 算分函数条件
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        // 原始的查询条件
                        boolQuery,
                        // 算分函数 数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 算分函数
                               new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                       // 筛选条件 （哪些文档需要重新计算得分）
                                       QueryBuilders.termQuery("isAD",true),
                                       // 计算得分的方法  weight直接给一个常量分值
                                       ScoreFunctionBuilders.weightFactorFunction(10)
                               )
                        }
                         // 加权模式: (算分 和 原始得分 如何计算 ) 默认相乘
                ).boostMode(CombineFunction.MULTIPLY);

        source.query(functionScoreQueryBuilder);
    }

    public static void main(String[] args) {
        String a = "";
        String b = " ";
        System.out.println(StringUtils.isBlank(a));
        System.out.println(StringUtils.isBlank(b));
        System.out.println(StringUtils.isEmpty(a));
        System.out.println(StringUtils.isEmpty(b));
    }
}
